import { ref } from 'vue'

type LoadingOptions = {
  title?: string
  timer?: number // 改为可选，不是每个show都需要timer
}

const showLoading = ref(false)
const loadingTitle = ref('Loading...')
let loadingCount = 0 // 改用计数方式
let hideTimer: NodeJS.Timeout | null = null
const REQUEST_DELAY = 300

export function useLoading() {
  const show = (opt?: LoadingOptions) => {
    if (hideTimer) {
      clearTimeout(hideTimer)
      hideTimer = null
    }

    loadingCount++

    if (opt?.title) {
      loadingTitle.value = opt.title
    }

    showLoading.value = true

    // 可选：定时自动关闭
    if (opt?.timer && opt.timer > 0) {
      setTimeout(() => {
        hide()
      }, opt.timer)
    }
  }

  const hide = () => {
    loadingCount = Math.max(0, loadingCount - 1)
    if (loadingCount > 0) {
      return
    }
    // 清除之前的定时器
    if (hideTimer) {
      clearTimeout(hideTimer)
    }

    hideTimer = setTimeout(() => {
      showLoading.value = false
      hideTimer = null
    }, REQUEST_DELAY)
  }

  const setTitle = (title?: string) => {
    if (title) loadingTitle.value = title
  }

  // 强制关闭（用于异常情况）
  const forceHide = () => {
    loadingCount = 0
    if (hideTimer) {
      clearTimeout(hideTimer)
      hideTimer = null
    }
    showLoading.value = false
  }

  return {
    show,
    hide,
    setTitle,
    forceHide,
    showLoading,
    loadingTitle
  }
}
